from datetime import datetime

from mongoengine import Document
from mongoengine import queryset_manager
from mongoengine.fields import StringField, EmailField, DateTimeField, \
    BooleanField


class BaseDocument(Document):
    create_at = DateTimeField()
    update_at = DateTimeField()
    is_del = BooleanField(default=False)

    meta = {'abstract': True}

    def save(self, *args, **kwargs):
        if not self.create_at:
            self.create_at = datetime.now()
        self.update_at = datetime.now()
        return super(BaseDocument, self).save(*args, **kwargs)

    @queryset_manager
    def objects(doc_cls, queryset):
        """过虑已删除的数据"""
        return queryset(is_del=False)


class BlogPost(Document):
    title = StringField(required=True, max_length=200)


class UserDocument(BaseDocument):
    username = StringField(max_length=32)
    password = StringField(max_length=256)
    email = EmailField()
    role = StringField(max_length=32)
    is_active = BooleanField(default=True)
